import json
import os
import re
import  pymongo

from PIL import Image
from io import BytesIO

def response(flow):
    # 请求url
    url = flow.request.url
    res = flow.response

    # 相应内容
    if 'client.action?functionId=search' in url:
        res_data = json.loads(res.text)['wareInfo']

        # print(res_data,type(res_data))
        for item in res_data:
            product_info = {}
            # 产品ID
            product_info['spuId'] = item['spuId']
            product_info['wname'] = item['wname']

            # 产品好评比例
            product_info['good'] = item['good']

            # 产品价格
            product_info['jdPrice'] = item['jdPrice']

            # 产品图片名称
            product_info['imageurl'] = get_product_image_name(item['imageurl'])
            product_info['listImgUrl'] = get_product_image_name(item['listImgUrl'])
            product_info['longImgUrl'] = get_product_image_name(item['longImgUrl'])


            col=get_mongo_col('jd','phone')

            product=col.find_one({"spuId":item['spuId']})

            if product :
                col.delete_one({"spuId":item['spuId']})
                col.insert(product_info)
            else:
                col.insert(product_info)



    if 'image' in res.headers['content-type']:
        if 'mobilecms' in url:
            imagename = get_product_image_name(url)
            print(imagename)
            print(url)

            img=Image.open(BytesIO(res.content))
            img.save(os.path.join("/root/image",imagename))


# 获取产品图片名称
def get_product_image_name(url):
    image_name=re.search('\w+\.jpg|\w+.png|\w+.jpeg',str(url))
    if image_name is not None:
        image_name = image_name.group()

    return image_name


# 保存产品数据到MongoDB
def get_mongo_col(db,col):
    myclient = pymongo.MongoClient("mongodb://192.168.0.21:27017")
    mydb = myclient[db]
    mycol = mydb[col]
    return mycol



